using Config;
using Koakuma.Game.Characters;
using Koakuma.Game.ECS;
using TGame.ECS;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Koakuma.Game.UI
{
    public class BattleUIBossHPBar : MonoBehaviour
    {
        public Image imgHP;
        public SlicedFilledImage imgFlash;
        public TextMeshProUGUI txtName;

        private CharacterAttributeComponent attributeComponent;
        private float targetFlashValue;
        private float flashValueVelocity;

        public void BindCharacter(ECSEntity target)
        {
            attributeComponent = target.GetComponent<CharacterAttributeComponent>();

            double currentHP = CharacterHelper.GetAttributeD(attributeComponent, CharacterAttributeType.CurrentHP);
            double maxHP = CharacterHelper.GetAttributeD(attributeComponent, CharacterAttributeType.MaxHP);
            targetFlashValue = (float)(currentHP / maxHP);
            imgHP.fillAmount = targetFlashValue;
            if (imgFlash != null)
            {
                imgFlash.fillAmount = targetFlashValue;
            }

            CharacterComponent characterComponent = target.GetComponent<CharacterComponent>();
            CharacterConfig characterConfig = CharacterConfig.ByID(characterComponent.configID);
            txtName.text = I18N.GetString(characterConfig.Name);
            UpdateHP();
            gameObject.SetActive(true);
        }

        public void UnbindCharacter()
        {
            attributeComponent = null;
            gameObject.SetActive(false);
        }

        private void Update()
        {
            if (attributeComponent == null)
                return;

            if (imgFlash != null)
            {
                imgFlash.fillAmount = Mathf.SmoothDamp(imgFlash.fillAmount, targetFlashValue, ref flashValueVelocity, 0.05f);
                imgFlash.enabled = !Mathf.Approximately(imgFlash.fillAmount, targetFlashValue);
            }
        }

        public void UpdateHP()
        {
            double currentHP = CharacterHelper.GetAttributeD(attributeComponent, CharacterAttributeType.CurrentHP);
            double maxHP = CharacterHelper.GetAttributeD(attributeComponent, CharacterAttributeType.MaxHP);
            targetFlashValue = (float)(currentHP / maxHP);
            imgHP.fillAmount = targetFlashValue;
        }
    }
}
